package com.mingyizhudao.app.view;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import com.dixiang.framework.network.URLHandler;
import com.dixiang.framework.utils.AlertDialogs;
import com.dixiang.framework.utils.FragmentUtils;
import com.mingyizhudao.app.R;
import com.mingyizhudao.app.utils.CommonUtils;
import com.mingyizhudao.app.utils.Constants;
import com.mingyizhudao.app.view.discover.DiscoverFragment;
import com.mingyizhudao.app.view.home.HomeFragment;
import com.mingyizhudao.app.view.mine.MineFragment;
import com.mingyizhudao.app.view.recommend.RecommendFragment;
import com.umeng.update.UmengUpdateAgent;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

public class MainActivity extends MYBaseActivity {
	private static final String TAG = "UpdateManager";
	private static final String PARAM_OS = "os";
	private static final String PARAM_OS_VERSION = "os_version";
	private static final String PARAM_DEVICE = "device";
	private static final String PARAM_APP_VERSION = "app_version";
	// private static final String URL = "http://mingyihz.com/api/appversion?";
	
	private static final String URL = "http://api.mingyizhudao.com/api2/appversion?";
	private final static String ENCODING = "UTF-8";
	private String CurAPPDLURL;
	private static final String UPDATE_SERVERAPK = "MYZD.apk";

	private static final int SHOW_FORCE_UPDATE_DLG = 101;
	private static final int SHOW_NEED_UPDATE_DLG = 102;

	private static final int DOWNLOAD_APK_PROGRESS = 103;//更新下载进度的标记
	private static final int DOWNLOAD_SUCCESS = 104;
	private static final int DOWNLOAD_FAIL = 105;
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {


				case SHOW_NEED_UPDATE_DLG:
					showUpdateDlg();
					break;

				case SHOW_FORCE_UPDATE_DLG:
					showForceUpdateDlg();
					break;
					
				case DOWNLOAD_APK_PROGRESS: {
					if (dlApkProgressDlg != null) {
						dlApkProgressDlg.setProgress(mDownloadApkProgress);
					}
					break;
				}
				case DOWNLOAD_FAIL: {
					Toast.makeText(getApplicationContext(), "Download apk fail",
							Toast.LENGTH_SHORT).show();
					if (dlApkProgressDlg != null) {
						dlApkProgressDlg.dismiss();
						dlApkProgressDlg = null;
					}
					break;
				}
				case DOWNLOAD_SUCCESS: {
					Toast.makeText(getApplicationContext(), "Download apk success",
							Toast.LENGTH_SHORT).show();
					if (dlApkProgressDlg != null) {
						dlApkProgressDlg.dismiss();
						dlApkProgressDlg = null;
					}
					installNewApk();
					break;
				}
				default:
					break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_main);
		super.onCreate(savedInstanceState);
		activity = this;
		UmengUpdateAgent.setUpdateOnlyWifi(false);
		UmengUpdateAgent.update(this);
		checkVersion();
		getDensity();// 获取手机屏幕信息
		initMenuView();
		FragmentUtils.putDefaultFragment(this, R.id.container,
				new HomeFragment());
	}

	@Override
	public void initHeaderView() {

	}

	@Override
	protected void onResume() {
		super.onResume();

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	public void onMenuChange(View view) {

		switch (view.getId()) {
		case R.id.rb1:
			FragmentUtils.goToFragment(activity, HomeFragment.class,
					R.id.container);
			break;
		case R.id.rb2:
			FragmentUtils.goToFragment(activity, RecommendFragment.class,
					R.id.container);
			break;
		case R.id.rb3:
			FragmentUtils.goToFragment(activity, DiscoverFragment.class,
					R.id.container);
			break;
		case R.id.rb4:
			FragmentUtils.goToFragment(activity, MineFragment.class,
					R.id.container);
			break;
		default:
			break;
		}
	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			AlertDialogs.getAlertDialog(activity).showAlertDialog("您确定退出名医主刀?",
					new OnClickListener() {
						@Override
						public void onClick(View arg0) {
							System.exit(0);
						}
					});
		}
		return true;
	}

	// 依次屏幕密度， 屏幕高度，屏幕宽度,状态栏高度
	private void getDensity() {

		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		MYApplication.density = dm.density;
		MYApplication.heightPixels = dm.heightPixels;
		MYApplication.widthPixels = dm.widthPixels;
		MYApplication.startheight = CommonUtils.getStatusHeight(this);
	}
	
	public void checkVersion() {
		new Thread(new Runnable() {

			@Override
			public void run() {

				String osv = getOsVersion();
				String device = getDeviceName();
				String appv = getCurAPPV();

				String url = URL + PARAM_OS + "=android&" + PARAM_OS_VERSION
								+ "=" + osv + "&" + PARAM_DEVICE + "=" + device + "&"
								+ PARAM_APP_VERSION + "=" + appv;

				url = url.replaceAll(" ", "%20");
				String respone = doHttpGet(URLHandler.getEncryptUrl(url));
				parseJson(respone);
			}
		}).start();
	}

	
	public void downApk() {
		if (CurAPPDLURL == null || CurAPPDLURL.isEmpty()) {
			return;
		}
		new Thread(new Runnable() {

			@Override
			public void run() {
				HttpClient client = new DefaultHttpClient();
				HttpGet get = new HttpGet(URLHandler.getEncryptUrl(CurAPPDLURL));
				//Log.e("url", CurAPPDLURL);
				HttpResponse response;
				try {
					response = client.execute(get);
					HttpEntity entity = response.getEntity();
					long length = entity.getContentLength();
					InputStream is = entity.getContent();
					FileOutputStream fileOutputStream = null;
					if (is != null) {
						File file = new File(getSavePath(), UPDATE_SERVERAPK);
						fileOutputStream = new FileOutputStream(file);
						byte[] b = new byte[1024];
						int charb = -1;
						int count = 0;
						while ((charb = is.read(b)) != -1) {
							fileOutputStream.write(b, 0, charb);
							count += charb;
							mHandler.sendEmptyMessage(DOWNLOAD_APK_PROGRESS);
							mDownloadApkProgress = (int) (count / length);
							
						}
					}
					fileOutputStream.flush();
					if (fileOutputStream != null) {
						fileOutputStream.close();
					}
					mHandler.sendEmptyMessage(DOWNLOAD_SUCCESS);
					
				} catch (Exception e) {
					mHandler.sendEmptyMessage(DOWNLOAD_FAIL);
				}
			}
		}).start();
	}

	private String doHttpGet(String url) {
		HttpClient client = new DefaultHttpClient();
		HttpGet get = new HttpGet(url);
		String res = null;
		try {
			HttpResponse respone = client.execute(get);
			res = getContent(respone);
		} catch (ClientProtocolException e) {

		} catch (IOException e) {
		}

		return res;
	}

	private String getContent(HttpResponse response) {
		HttpEntity entity = response.getEntity();
		byte[] bytes;
		String content = null;

		try {
			bytes = EntityUtils.toByteArray(entity);
			content = new String(bytes, ENCODING);
			entity.consumeContent();
		} catch (IOException e) {
		}
		return content;
	}
	private void parseJson(String str) {
		if (str == null || str.isEmpty()) {
			return;
		}

		try {
			JSONObject obj = new JSONObject(str).getJSONObject("appversion");

			String appv = obj.getString("app_version");
			String downloadVersion = obj.getString("cur_app_version");

			int appversion = Integer.parseInt(appv);
			int downLoadVersion = Integer.parseInt(downloadVersion);
			if (appversion >= downLoadVersion) {
				return;
			}

			CurAPPDLURL = obj.getString("cur_app_dl_url");
			int force = obj.getInt("force_update");
			if (TextUtils.isEmpty(CurAPPDLURL)) {
				force = Constants.Update_Status.NO_UPDATE;
			}
			// force = GlobalUtils.Update_Status.NO_UPDATE;

			if (force == Constants.Update_Status.NEED_UPDATE) {
				mHandler.sendEmptyMessage(SHOW_NEED_UPDATE_DLG);

			} else if (force == Constants.Update_Status.FORCE_UPDATE) {

				mHandler.sendEmptyMessage(SHOW_FORCE_UPDATE_DLG);
			}

		} catch (JSONException e) {

		}
	}
	private String getCurAPPV() {
		PackageManager pm = activity.getPackageManager();
		String V = null;
		try {
			PackageInfo pi = pm.getPackageInfo(activity.getPackageName(), 0);
			V = String.valueOf(pi.versionCode);
		} catch (NameNotFoundException e) {

		}
		return V;
	}

	private String getOsVersion() {
		return Build.VERSION.RELEASE;
	}

	private String getDeviceName() {
		return Build.MANUFACTURER + Build.MODEL;
	}

	private File getSavePath() {
		return Environment.getExternalStorageDirectory();
	}
	
	
	private AlertDialog updateAlertDlg;
	private ProgressDialog dlApkProgressDlg;
	
	private int mDownloadApkProgress = 0;//进度值
	
	
	private void initDlProgressDlg() {
		dlApkProgressDlg = ProgressDialog.show(this, "软件下载", "正在下载，请稍候... ");
	}
	private void showForceUpdateDlg() {
		if (updateAlertDlg != null) {
			return;
		}

		AlertDialog.Builder builder = new AlertDialog.Builder(activity)//new ContextThemeWrapper(MainActivity.this, R.style.MyTheme)
				.setTitle("版本检测")
				// 设置对话框标题
				.setIcon(R.drawable.ic_launcher)
				.setMessage("有更新的版本")
				.setPositiveButton("立即更新",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								Toast.makeText(getApplicationContext(),
										"正在下载", Toast.LENGTH_SHORT)
										.show();
								initDlProgressDlg();
								downApk();

								updateAlertDlg.dismiss();
								updateAlertDlg = null;
							}

						});
		updateAlertDlg = builder.create();
		updateAlertDlg.setCanceledOnTouchOutside( false );
		updateAlertDlg.show();
	}
	
	
	
	private void showUpdateDlg() {
		if (updateAlertDlg != null) {
			return;
		}

		AlertDialog.Builder builder = new AlertDialog.Builder(activity)//MainActivity.this, R.style.MyTheme)
				.setTitle("版本检测")
				// 设置对话框标题
				.setIcon(R.drawable.ic_launcher)
				.setMessage("有更新的版本")
				.setPositiveButton("立即更新",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								Toast.makeText(getApplicationContext(),
										"正在下载", Toast.LENGTH_SHORT)
										.show();
								initDlProgressDlg();
								downApk();

								updateAlertDlg.dismiss();
								updateAlertDlg = null;
							}

						})
				.setNegativeButton("稍后更新",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								updateAlertDlg.dismiss();
								updateAlertDlg = null;
//								if (mUpdateStatus == Constants.Update_Status.FORCE_UPDATE) {
//									finish();
//								}
							}
						});
		updateAlertDlg = builder.create();
		updateAlertDlg.setCanceledOnTouchOutside( false );
		updateAlertDlg.show();
	}

	public void installNewApk() {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(new File(Environment
				.getExternalStorageDirectory(), UPDATE_SERVERAPK)),
				"application/vnd.android.package-archive");
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
				| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
		activity.startActivity(intent);
	}
}
